package com.excel.sys.service.impl;

import com.excel.sys.service.ImportExcelService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Service
public class ImportExcelServiceImpl implements ImportExcelService {

    @Override
    public Map<String, Object> importExcel(MultipartFile file) {
        Map<String, Object> res = new HashMap<>();
        try {
            //创建工作薄 根据Eexcel 版本 创建 HSSFWorkbook（2003）XSSFWorkbook（2007）
            Workbook wb = new XSSFWorkbook(file.getInputStream());
            //获取 Sheet 参数：索引
            Sheet sheet = wb.getSheetAt(0);
            //获取 Sheet 中的每一行，每一个单元格
            List<Map<String,Object>> users = new ArrayList<>();
            for (int i = 1; i <=sheet.getLastRowNum() ; i++) {
                //获取 行
                Row row = sheet.getRow(i);
                Object [] values = new Object[row.getLastCellNum()];
                for (int j = 0; j <row.getLastCellNum() ; j++) {
                    //根据索引获取每一个单元格
                    Cell cell = row.getCell(j);
                    //获取每一个单元格的内容
                    Object value = getCellValue(cell);
                    values[j] = value;
                }
                Map<String,Object> user = new HashMap<>();
                user.put("id",values[0]);
                user.put("name",values[1]);
                user.put("password",values[2]);
                users.add(user);
            }
            System.out.println(users);

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

}
